<?php

class Icon extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('UrlUtil');
        $this->load->library('common/CommonEnum');
        $this->load->model('Model_urls');
        $this->load->service('Service_icon');
    }

    public function index()
    {
        $index = (int)$this->Service_icon->getConfigVal(CommonEnum::ICON_INDEX_CONFIG_ID);
        $limit = (int)$this->Service_icon->getConfigVal(CommonEnum::ICON_LIMIT_CONFIG_ID);
        $lastId = $index;

        $cond = ['icon_sina' => '', 'status' => 0, 'id > ' => $index];
        $list = $this->Model_urls->getList(1, $cond, $limit, 'ASC');
        foreach ($list as $item) {
            $domain = UrlUtil::getHost($item['url']);
            $icon = $this->Service_icon->index($domain);
            if (!empty($icon)) {
                echo $item['id'] . '|' . $item['url'] . '|' . $icon . '<br/>' . PHP_EOL;
                $data['id'] = $item['id'];
                empty($item['icon']) && $data['icon'] = $icon;
                $data['icon_sina'] = $icon;  // "https://images.weserv.nl/?url="
            } else {
                $data['id'] = $item['id'];
                $icon = $this->Service_icon->make($item['title']);
                empty($item['icon']) && $data['icon'] = $icon ? : "https://{$domain}/favicon.ico";
                $data['icon_sina'] = $icon ? : "https://{$domain}/favicon.ico";
            }
            $this->Model_urls->update($data);
            $lastId = $item['id'];
        }
        $this->load->database('default', true);
        $this->load->model('Model_configs');
        $this->Model_configs->update(['id' => CommonEnum::ICON_INDEX_CONFIG_ID, 'value' => $lastId]);
    }

}
